import store from "../store/index.js";
import { Base64 } from "@/common/base64Util.js";
import { goBack } from "@/common/util.js";

const b = new Base64();
const loginPath = "/pages/common/login/login"; // 登录页地址

let platform = uni.getSystemInfoSync().platform;

if (platform == "android") {
  platform = "Android";
}
if (platform == "ios") {
  platform = "IOS";
}

var appUrl = "http://localhost:5173/api";
var webUrl = "/port";

uni.addInterceptor("request", {
  invoke(args) {
    if (!args.header) {
      args.header = {};
    }

    let { getToken, getTokenType } = store.getters;

    if (!args.url.startsWith("http")) {
      if (platform == "h5") {
        args.url = webUrl + args.url;
      } else {
        args.url = appUrl + args.url;
      }

      const header = {
        Accept: "application/json",

        OS: platform,
        AppVersion: "1.0.0",
        "Tenant-Id": "000010",
        terminal: platform,
        systemType: "hg-app",
        Authorization: `Basic aGJhcHA6YWMwJEBXd3o3OQ==`,
        ...args.header,
      };

      if (getToken && getTokenType) {
        header["Blade-Auth"] = `${getTokenType} ${getToken}`;
      }
      args.header = header;
    }

    if (!args.hideLoad) {
      uni.showLoading({
        mask: true,
      });
    }
  },
  success(args) {
    uni.hideLoading();
    var message = "";
    if (args.data) {
      message =
        args.data.error_description || args.data.message || args.data.msg;
    }
    if (args.statusCode == 401) {
      uni.showToast({
        title: message || "未知错误",
        icon: "none",
      });
      goBack(loginPath, 4);
      store.commit("logOut");
    } else if (
      args.statusCode != 200 ||
      (args.data.code && args.data.code != 200)
    ) {
      uni.showToast({
        title: message || "未知错误",
        icon: "none",
      });
    }
  },
  fail(err) {
    var message = "";
    if (err.data) {
      message = err.data.error_description || err.data.message;
    }
    uni.showToast({
      title: message || "未知错误",
      icon: "none",
    });
    uni.hideLoading();
  },
  complete(res) {
    uni.hideLoading();
  },
});
